package com.mhs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mhs.entity.User;
import com.mhs.exception.BizException;
import com.mhs.mapper.SysRoleMapper;
import com.mhs.mapper.UserMapper;
import com.mhs.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;
    
    
    @Resource
    private SysRoleMapper sysRoleMapper;

    /**
     * 根据用户名和密码进行登陆
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(queryWrapper);
        //如果没有查询到用户就抛出异常
        if(Objects.isNull(user)){
            throw new RuntimeException(new BizException("用户名或者密码错误"));
        }
        //查询对应的权限信息
        //从数据库中查询用户对应的权限
//        List<String> list = sysMenuMapper.selectPermsByUserId(user.getId());
        //此处进行简化,对每个角色等级进行划分权限,只需要查询用户在系统中的角色
        List<String> list = sysRoleMapper.selectRoleKeyByUserId(user.getId());
        //把数据封装成UserDetails返回
        return new LoginUser(user,list);
    }
    
    
    
    
}
